﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.IO;
using System.Xml;
using System.ServiceModel;

namespace HomeFramework.Core
{
    public class FlatWsdlBuilder
    {
        public static void GenerateWsdl(Stream output, ServiceEndpoint endpoint)
        {
            var wsdl = new WsdlExporter();
            wsdl.ExportEndpoint(endpoint);

            var export = wsdl.GetGeneratedMetadata();

            var doc = new XmlDocument();
            var xnm = new XmlNamespaceManager(doc.NameTable);
            xnm.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
            xnm.AddNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/");
            xnm.AddNamespace("wsx", "http://schemas.xmlsoap.org/ws/2004/09/mex");
            xnm.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            using (var m = new MemoryStream())
            {
                using (var w = XmlWriter.Create(m))
                    export.WriteTo(w);

                m.Position = 0;
                doc.Load(m);

                var definition = doc.SelectSingleNode("//wsdl:definitions", xnm);
                var xsdschema = definition.SelectSingleNode("//wsdl:types", xnm);
                xsdschema.RemoveAll();
                var schemas = doc.SelectNodes("//wsx:MetadataSection/xs:schema", xnm);
                foreach (XmlNode node in schemas)
                    xsdschema.AppendChild(node);

                using (var x = new StreamWriter(output, Encoding.UTF8))
                    x.Write(definition.OuterXml);
            }
        }
    }
}
